<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket Example</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.6.1/sockjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
<h1>SockJS with STOMP Example</h1>
<input type="text" id="messageInput" placeholder="Type a message">
<button onclick="sendMessage()">Send</button>
<br>
<input type="text" id="publicMessageInput" placeholder="Type a message">
<button onclick="sendPublicMessage()">Send</button>
<div id="messageArea"></div>

<script>
    const socket = new SockJS('/webSocket'); // SockJS 连接地址
    const stompClient = Stomp.over(socket);

    stompClient.connect({}, function(frame) {
        const urlSearchParams = new URLSearchParams(window.location.search);
        const toUser = urlSearchParams.get('toUser');
        console.log('SockJS with STOMP connection established,' + toUser);
        stompClient.subscribe('/topic/messages', function(message) {
            console.log('收到公共消息：' + message);
            const messageArea = document.getElementById('messageArea');
            // const messageText = JSON.parse(message.body);
            messageArea.innerHTML += '<p>' + message.body + '</p>';
        });

        stompClient.subscribe('/user/' + toUser + '/to/user/message', function (message) {
            console.log('收到一对一消息：' + message)
            const messageArea = document.getElementById('messageArea');
            // const messageText = JSON.parse(message.body);
            messageArea.innerHTML += '<p>' + message.body + '</p>';
        })
    });

    function sendMessage() {
        const messageInput = document.getElementById('messageInput');
        const message = messageInput.value;

        const urlSearchParams = new URLSearchParams(window.location.search);
        const type = urlSearchParams.get('type');
        const toUser = urlSearchParams.get("toUser")

        stompClient.send('/app/send', {}, JSON.stringify({type:type,content:message,sender:"System",toUser:toUser}));
        messageInput.value = '';
    }

    function sendPublicMessage() {
        const messageInput = document.getElementById('publicMessageInput');
        const message = messageInput.value;

        const urlSearchParams = new URLSearchParams(window.location.search);
        const type = urlSearchParams.get('type');
        const toUser = urlSearchParams.get("toUser")

        stompClient.send('/app/news/notify/all', {}, JSON.stringify({type:type,content:message,sender:"System",toUser:toUser}));
        messageInput.value = '';
    }
</script>
</body>
</html>